<?php
class TopicController extends \BaseController {


    //专题首页
    public function getIndex() {
        $topics = Topic::all();
        foreach($topics as $key => $topic) {
            $topics[$key]->pictures = DB::table('topic_pictures')
                                    ->join('pictures', 'topic_pictures.picture_id', '=', 'pictures.id')
                                    ->select(array('pictures.id', 'pictures.thumb'))
                                    ->where('topic_pictures.topic_id', '=', $topic->id)
                                    ->take(5)->get();
        }

        return View::make('front/topic_index')
                    ->with('topics', $topics);
    }

    //专题详情页面
    public function getInfo($topicId) {
        $topicInfo = Topic::find($topicId);
        $pictures = DB::table('topic_pictures')
                        ->join('pictures', 'topic_pictures.picture_id', '=', 'pictures.id')
                        ->where('topic_pictures.topic_id', '=', $topicId)->paginate(20);

        foreach($pictures as $key => $picture) {
            $pictures[$key]->userInfo = User::find($picture->user_id);
        }

        return View::make('front/topic_info')
                    ->with('pictures', $pictures)
                    ->with('topicInfo', $topicInfo);
    }

    //创建专题
    public function getCreate() {
        if(Auth::check()) {
            return View::make('front/topic_create_form');
        }
    }

    public function postCreate() {
        if(Auth::check()) {
            $userId = Auth::user()->id;
            $data = Input::all();

            $destinationPath = Config::get('app.topic_upload_path');

            $file = Input::file('thumb');

            $filename_thumb = str_random(32);
            $fileExt = $file->getClientOriginalExtension();

            Image::make($file->getRealPath())->resize('400', null, function($constraint) {
                    $constraint->aspectRatio();
                })->save($destinationPath . $filename_thumb . '.' . $fileExt);

            $topic = new Topic();

            $topic->name = $data['name'];
            $topic->description = $data['description'];
            $topic->thumb = $filename_thumb . '.' . $fileExt;
            $topic->user_id = $userId;
            $topic->save();

            return Redirect::to('/topic/management')->with('message', '专题创建成功，是否给专题添加图片？');
        }
    }

    //专题编辑
    public function getEdit($topicId) {
        if(Auth::check()) {
            if(!$this->isAllow($topicId)) {
                return array('error' => '没有权限！');
            }

            $topicInfo = Topic::find($topicId);

            return View::make('front/topic_edit_form')
                        ->with('topicInfo', $topicInfo);
        }
    }

    public function postEdit() {
        if(Auth::check()) {
            $userId = Auth::user()->id;
            $topicId = Input::get('topic_id');

            $data = Input::all();

            if(!$this->isAllow($topicId)) {
                return array('error' => '没有权限！');
            }

            $topic = Topic::find($topicId);
            $topic->name = $data['name'];
            $topic->description = $data['description'];
            if($data['thumb']) {
                $destinationPath = Config::get('app.topic_upload_path');

                $file = Input::file('thumb');

                $filename_thumb = str_random(32);
                $fileExt = $file->getClientOriginalExtension();

                Image::make($file->getRealPath())->resize('400', null, function($constraint) {
                        $constraint->aspectRatio();
                    })->save($destinationPath . $filename_thumb . '.' . $fileExt);

                $topic->thumb = $filename_thumb . '.' . $fileExt;
            }

            $topic->save();


            return Redirect::to('/topic/management')->with('message', '修改成功');
        }

    }


    //专题管理（注册用户）
    public function getManagement() {
        if(Auth::check()) {
            $userId = Auth::user()->id;
            $topics = Topic::where('user_id', '=', $userId)->paginate(4);

            return View::make('front/topic_management')
                            ->with('topics', $topics);
        }
    }


    //专题图片管理
    public function getEditPictures($topicId) {
        if(Auth::check()) {
            $userId = Auth::user()->id;

            if(!$this->isAllow($topicId)) {
                return array('error' => '没有权限！');
            }

            $topicInfo = Topic::find($topicId);

            $userPictures = Picture::where('user_id', '=', $userId)
                        ->select(array('id', 'thumb'))
                        ->get();

            $selectedPictures = DB::table('topic_pictures')
                                    ->where('topic_id', '=', $topicId)
                                    ->get();




            foreach($userPictures as $key => $userPicture) {

                foreach($selectedPictures as $selectedPicture) {

                    if($userPicture->id == $selectedPicture->picture_id) {

                        $userPictures[$key]->selected = 'selected';
                        break;

                    }else {
                        $userPictures[$key]->selected = '';
                    }
                }

            }


            return View::make('front/topic_edit_pictures')
                        ->with('topicInfo', $topicInfo)
                        ->with('userPictures', $userPictures);

        }

    }

    public function postEditPictures() {
        if(Auth::check()) {
            $userId = Auth::user()->id;
            $topicId = Input::get('topic_id');
            $picture_ids = Input::get('picture_ids');

            if(!$this->isAllow($topicId)) {
                return array('error' => '没有权限！');
            }

            DB::table('topic_pictures')->where('topic_id', '=', $topicId)->delete();

            if(empty($picture_ids)) {
                return Redirect::to('/topic/management')
                            ->with('error', '专题中未添加图片！');
            }

            foreach($picture_ids as $picture_id) {
                DB::table('topic_pictures')->insert(
                    array(
                        'topic_id' => $topicId,
                        'picture_id' => $picture_id
                    )
                );


            }

            return Redirect::to('/topic/management')->with('message', '修改成功');

        }

    }


    //专题删除
    public function getDelete($topicId) {

        if(Auth::check()) {
            $userId = Auth::user()->id;
            $topicCount = Topic::whereRaw('id = ? and user_id = ?', array($topicId, $userId))->count();

            if(!$this->isAllow($topicId)) {
                return array('error' => '没有权限！');
            }

            if($topicCount) {
                DB::table('topic_pictures')->where('topic_id', '=', $topicId)->delete();
                Topic::where('id', '=', $topicId)->delete();
                return Redirect::to('/topic/management')->with('message', '您删除了一个专题！');
            } else {
                return App::abort(404);
            }
        }
    }


    //权限判断
    public function isAllow($topicId) {
        $userId = Auth::user()->id;
        $allowDelete = Topic::whereRaw('id = ? and user_id = ?', array($topicId, $userId))->get();

        if(empty($allowDelete)) {
            return false;
        }else {
            return true;
        }
    }










}
